#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/3
# @Author  : LiJun
# @Email   : lijun@tianyancha.com
# @Version : 1.0.0


import logging
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from appium.webdriver import WebElement
from appium.webdriver.webdriver import WebDriver
from appium.webdriver.common.mobileby import MobileBy as By

import yaml
from conf import config as cf

class BasePage:
    def __init__(self, driver_base: WebDriver = None, element:dict=None):
        self.driver = driver_base
        # self.driver.press_keycode(4)

        if element is None:
            with open(f"{cf.ELEMENT_DIR}/element.yaml", "r", encoding="utf-8") as f:
                self.element = yaml.safe_load(f)
        else:
            self.element = element

    def log(self, message, type="info"):
        if type == "info":
            logging.info(message)
        elif type == "warn":
            logging.warning(message)
        elif type == "error":
            logging.error(message)

    def by_maps(self, element):
        maps = {
            "ID"               : By.ID,
            "XPATH"            : By.XPATH,
            "NAME"             : By.NAME,
            "PARTIAL_LINK_TEXT": By.PARTIAL_LINK_TEXT,
            "CSS": By.CSS_SELECTOR,
            "UISELECTOR_TEXT" : By.ANDROID_UIAUTOMATOR,
        }
        return (maps[element["by"].upper()], element["locate"])


    def find(self, by, locate, outtime=3):
        try:
            ele:WebElement = WebDriverWait(self.driver, outtime, 1).until(EC.presence_of_element_located((by, locate)))
            return ele
        except Exception as e:
            return None

    def finds(self, by, locate, outtime=3):
        eles: WebElement = WebDriverWait(self.driver, outtime, 1).until(EC.presence_of_all_elements_located((by,
                                                                                                            locate)))
        return eles

    def find_click(self, by, locate, outtime=3):
        self.find(by, locate, outtime).click()
    
    def scroll_find(self, locate, outtime=3):
        element = f'new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector(' \
                  f').text("{locate}").instance(0));'
        ele = self.find(by=By.ANDROID_UIAUTOMATOR, locate=element, outtime=outtime)
        return ele

    def swipt_find(self, by, locate, number=4, outtime=3):

        for i in range(1, number+1):
            ele = self.find(by, locate, outtime)
            if not ele:
                size = self.driver.get_window_size()
                height = size["height"]
                width = size["width"]
                start_x = width * 0.5
                start_y = height * 0.85
                end_y = height * 0.3

                self.log(f"第{i}次滑动屏幕")
                self.driver.swipe(start_x=start_x, end_x=start_x, start_y=start_y, end_y=end_y, duration=2000)
                continue
            return ele



    def find_send(self, by, locate, message, outtime=3):
        self.find(by, locate, outtime).send_keys(message)

    def get_toast(self):
        ele = self.find(*self.by_maps(self.element["Toast"]))

        return ele.text

    def get_pop(self):
        pop_title = self.find(*self.by_maps(self.element["PopTitle"])).text

        return pop_title

    def back_home_page(self):
        count = 0
        while count < 10:
            if self.find(*self.by_maps(self.element["News"]), outtime=1):
                break
            self.driver.back()
            count += 1
